package cn.saas.video;

import android.Manifest;
import android.content.Intent;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.hw.videoprocessor.VideoProcessor;

import java.io.File;
import java.util.UUID;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;


@RuntimePermissions
public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_CODE_VIDEO = 0x001;
    private static final String TAG = "aaaaaa";

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView mtv = (TextView) findViewById(R.id.tv);
        mtv.setOnClickListener(v -> {
            startVideo();
        });
        requestPermission();

    }


    private void startVideo() {
        // 视频存放地址
        String baseDir = Environment.getExternalStorageDirectory() + "/" + this.getPackageName();
        String videoFilePath = baseDir + "/" + UUID.randomUUID() + ".mp4";
        File baseDirFile = new File(baseDir);
        if (!baseDirFile.exists()) {
            baseDirFile.mkdirs();
        }
        File file = new File(videoFilePath);
        if (file.exists()) {
            file.delete();
        }
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // 质量 0低 1高
        intent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, 10485760L);
        intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, FileUtils.getUriForFile(MainActivity.this, file));
        this.startActivityForResult(intent, REQUEST_CODE_VIDEO);
    }

    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void requestPermission() {
        startVideo();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_VIDEO:
                    Uri videoUri = data.getData();
                    String fromURI = FileUtils.getPathFromUri(this, videoUri);
                    String substring = FileUtils.getFilePath(this, videoUri).substring(FileUtils.getFilePath(this, videoUri).lastIndexOf("/") + 1);
//
                    String s = Environment.getExternalStorageDirectory() + "/" + getPackageName() + "/" + substring;
//                    String fromURI = FileUtils.getFilePath(this, videoUri);
//                    Log.e(TAG, "onActivityResult: " + fromURI);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            boolean success = true;
                            try {
                                Log.e(TAG, "run: " + s);
                                String basePath = FileUtils.getBasePath(MainActivity.this);
                                Log.e(TAG, "run: " + basePath);

                                MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                                retriever.setDataSource(s);
                                String width = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH); //宽
                                String height = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT); //高
                                String rotation = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);//视频的方向角度
                                long duration = Long.valueOf(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)) * 1000;//视频的长度

                                Log.e(TAG, "run: width " + width + "\nheight " + height);
                                VideoProcessor.processor(MainActivity.this)
                                        .input(s)
                                        .outHeight(Integer.parseInt(height) / 2)
                                        .outWidth(Integer.parseInt(width) / 2)
                                        .output(basePath + "/aaa.mp4")
                                        .progressListener(progress -> {
                                            Log.e(TAG, "run: " + progress);
                                        })
                                        .process();
                            } catch (Exception e) {
                                e.printStackTrace();
                                success = false;
                                Log.e(TAG, "run: Exception" + e.getMessage());
                            }
                            if (success) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Log.e(TAG, "run: run");
                                    }
                                });
                            }
                        }
                    }).start();
                    break;
            }
        }
    }
}